﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private DataTable suppl;
        private DataTable pharm;
        private delegate void Deleg();
        private Deleg del;
        private Guid guid;
        private struct Dict { public int id; public string text; }
        private Dict[] basema;
        //private Dict[] doctype;
        private DataTable dt_drugs;
        private DataTable dt_brand;
        private DataTable dt_drug_tmp;

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            dt_rep = new DataTable();
            guid = Guid.NewGuid();
            listBox1.Items.Add("Все");
            listBox2.Items.Add("(Все товары)");
            suppl = new DataTable();
            suppl.Load(ProcSel(conn, @"pas_SupplSel"));
            foreach (DataColumn dc in suppl.Columns)
            {
                if (dc.ColumnName != "Флаг") dc.ReadOnly = true;
                else dc.ReadOnly = false;
            }

            //listBox2.Items.Add("Все");
            pharm = new DataTable();
            pharm.Load(ProcSel(conn, @"pas_PharmSel"));
            foreach (DataColumn dc in pharm.Columns)
            {
                if (dc.ColumnName != "Флаг") dc.ReadOnly = true;
                else dc.ReadOnly = false;
            }

            //dataGridView2.DataSource = suppl.DefaultView;
            //dataGridView2.Columns[0].ReadOnly = false;
            //dataGridView2.RowHeadersVisible = false;
            //dataGridView2.Columns[0].Width = 30;
            //dataGridView2.Columns[1].Width = 40;
            //dataGridView2.Columns[2].Width = dataGridView2.Width - dataGridView2.Columns[0].Width - dataGridView2.Columns[1].Width - 20;
            //dataGridView2.Columns[3].Visible = false;
            //dataGridView2.Columns[4].Visible = false;
            //dataGridView2.Sort(dataGridView2.Columns[1], ListSortDirection.Ascending);
            DataTable dt_b = new DataTable();
            //DataTable dt_d = new DataTable();

            dt_b.Load(ProcSel(conn, @"pas_BaseMASel"));
            //dt_d.Load(ProcSel(conn, @"pas_DocTypeSel"));

            basema = new Dict[dt_b.Rows.Count];
            //doctype = new Dict[dt_d.Rows.Count];
            for(int i = 0; i < dt_b.Rows.Count; i++)
            {
                object[] ob = dt_b.Rows[i].ItemArray;
                basema[i].id = (int)ob[0];
                basema[i].text = ob[1].ToString();
                comboBox1.Items.Add(basema[i].text);
            }

            //for (int i = 0; i < dt_d.Rows.Count; i++)
            //{
            //    object[] ob = dt_d.Rows[i].ItemArray;
            //    doctype[i].id = (int)ob[0];
            //    doctype[i].text = ob[1].ToString();
            //    comboBox2.Items.Add(doctype[i].text);
            //}

            comboBox1.SelectedIndex = 0;
            //comboBox2.SelectedIndex = 0;
        }

        private SqlDataReader ProcSel(SqlConnection con, string procname)
        {
            SqlCommand com = con.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = procname;
            if (con.State == ConnectionState.Closed) con.Open();
            return com.ExecuteReader();
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);

                if (conn.State == ConnectionState.Closed) conn.Open();

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                guid = Guid.NewGuid();

                if (suppl != null)
                    foreach (DataRow dr in suppl.Rows)
                            if (Convert.ToBoolean(dr[namechcol]) == true)
                            {
                                myCommand.Parameters["@guid"].Value = guid;
                                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                                myCommand.Parameters["@del"].Value = false;
                                myCommand.Parameters["@nature"].Value = "sup";
                                myCommand.ExecuteNonQuery();
                            }

                if (dt_drug_tmp != null)
                        foreach (DataRow dr in dt_drug_tmp.Rows)
                            if (Convert.ToBoolean(dr[namechcol]) == true)
                            {
                                myCommand.Parameters["@guid"].Value = guid;
                                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                                myCommand.Parameters["@del"].Value = false;
                                myCommand.Parameters["@nature"].Value = "drug";
                                myCommand.ExecuteNonQuery();
                            }
                //if (pharm != null)
                //    foreach (DataRow dr in pharm.Rows)
                //            if (Convert.ToBoolean(dr[namechcol]) == true)
                //            {
                //                myCommand.Parameters["@guid"].Value = guid;
                //                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                //                myCommand.Parameters["@del"].Value = false;
                //                myCommand.Parameters["@nature"].Value = "pharm";
                //                myCommand.ExecuteNonQuery();
                //            }


                dt_rep.Load(RepProc(guid, conn));

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private SqlDataReader RepProc(Guid id, SqlConnection sqlcon)
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_CommDep_PriceTranslation";
            sqlcom.CommandTimeout = 300;

            sqlcom.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
            sqlcom.Parameters["@guid"].Value = id;

            sqlcom.Parameters.Add("@baseid", SqlDbType.Int);
            this.Invoke((Func<object>)(() => sqlcom.Parameters["@baseid"].Value = basema[comboBox1.SelectedIndex].id));

            return sqlcom.ExecuteReader();
        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "привязки прайсов поставщиков";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }



        private void HideResult(DataGridView buffview)
        {
            if (buffview.DataSource != null)
            {
                CurrencyManager cm = (CurrencyManager)buffview.BindingContext[buffview.DataSource];
                cm.SuspendBinding();
                int select = 0;
                int filter = 0;
                foreach (DataGridViewRow r in buffview.Rows)
                {
                    r.Visible = true;
                    r.DefaultCellStyle.BackColor = SystemColors.ControlLightLight;

                    //if (!Regex.Match(Convert.ToString(buffview[buffview.SortedColumn.Name, r.Index].Value), textBox1.Text, RegexOptions.IgnoreCase).Success)
                    //    r.Visible = false;

                    //if (checkBox1.Checked)
                    //    if (!Convert.ToBoolean(dataGridView1[namechcol, r.Index].Value)) r.Visible = false;

                    if (Convert.ToBoolean(buffview[namechcol, r.Index].Value))
                    {
                        select++;
                        r.DefaultCellStyle.BackColor = Color.Red;
                    }
                    if (r.Visible) filter++;
                }
                cm.ResumeBinding();
            }
        }



        private void button3_Click(object sender, EventArgs e)
        {
            int fl = 0;
            listBox1.Items.Clear();
            suppl = FiltFormShow("Поставщики", namechcol, "Поставщик", suppl);
            fl = 0;
            foreach (DataRow dr in suppl.Rows)
            {
                if (Convert.ToBoolean(dr["Флаг"]))
                {
                    fl++;
                    listBox1.Items.Add(dr["Поставщик"].ToString());
                }
            }
            if (fl == 0) listBox1.Items.Add("Все");

        }

        public DataTable FiltFormShow(string formname, string flname, string sort, DataTable dt)
        {
            PharmFilter.PharmFilter f = new PharmFilter.PharmFilter();
            f.Name = formname;
            f.dataGridView1.DataSource = dt.DefaultView;
            f.namechcol = flname;
            f.sortcoumn = sort;
            f.ShowDialog();
            f.Close();
            f = null;
            return dt;
        }

        //private void button4_Click_1(object sender, EventArgs e)
        //{
        //    int fl = 0;
        //    //listBox2.Items.Clear();
        //    pharm = FiltFormShow("Аптеки", namechcol, "Аптека", pharm);
        //    fl = 0;
        //    foreach (DataRow dr in pharm.Rows)
        //    {
        //        if (Convert.ToBoolean(dr["Флаг"]))
        //        {
        //            fl++;
        //            listBox2.Items.Add(dr["Аптека"].ToString());
        //        }
        //    }
        //    if (fl == 0) listBox2.Items.Add("Все");
        //}

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            DrugsFilter.DrugsFilter f2 = new DrugsFilter.DrugsFilter();
            DrugsFilter.DrugsFilter.StorProcParam[] spp = new DrugsFilter.DrugsFilter.StorProcParam[1];

            spp[0] = f2.StorProcParamIns("@arch", SqlDbType.VarChar, 20, "jhjhjh");

            SqlCommand myCommand = new SqlCommand();
            myCommand = f2.StorProc(myCommand, conn, "pas_AllDrugsSel", spp);

            if (dt_drugs == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drugs = new DataTable();
                    dt_drugs.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drugs.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    dt_brand = new DataTable();
                    dt_brand.Load(GetBrandTree(conn));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
                f2.rb = true;
            }
            if (dt_drug_tmp == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drug_tmp = new DataTable();
                    dt_drug_tmp.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drug_tmp.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
            }
            f2.sqlconn = conn;
            f2.namechcol = namechcol;
            f2.dt_drug = dt_drugs;
            f2.dt_drug_tmp = dt_drug_tmp;
            if (dt_drug_tmp.Rows.Count == 0)
                f2.dataGridView1.DataSource = f2.dt_drug.DefaultView;
            else
                f2.dataGridView1.DataSource = f2.dt_drug_tmp.DefaultView;
            f2.dt_br = dt_brand;
            f2.ShowDialog();
            listBox2.Items.Clear();
            foreach (DataRow dr in dt_drug_tmp.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true && dr.RowState != DataRowState.Deleted) listBox2.Items.Add(dr["Товар"]);
            }
            if (listBox2.Items.Count == 0) listBox1.Items.Add("(Все товары)");
            f2.Close();
        }

        private SqlDataReader GetBrandTree(SqlConnection sqlcon)
        {
            SqlCommand com = conn.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"pas_BrandTreeSel";

            return com.ExecuteReader();
        }
    }
}
